/*
 * GoogleDataHandler.java
 * 
 * Created on Nov 10, 2007, 8:05:20 PM
 */
package bloggerdesktop;

import com.google.gdata.client.*;
import com.google.gdata.data.*;
import com.google.gdata.data.extensions.*;
import com.google.gdata.util.*;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Hashtable;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.*;

/**
 *
 * @author Paul Schroeder, Christopher Kruse
 */
public class GoogleDataHandler {
    //Global variables and things we need for later.
    public final int BLOG_ID_OFFSET = 5;
    final String BLOGGER_URI = "http://www.blogger.com/feeds/";
    final String POST_SUFFIX = "posts/default";
    final String COMMENT_SUFFIX = "comments/default";
    GoogleService theService;
    String[] list;
    String[] rNumbers;
    String[] postNames;
    String[] postIds;
    Hashtable<String, String> blogTable = new Hashtable<String, String>();
    Hashtable<String, String> postTable = new Hashtable<String, String>();
    /**
     * Constructor
     * Create a new Instance of GoogleDataHandler
     * @param myService the google service used for callbacks.
     */
    public GoogleDataHandler(GoogleService myService) {
        theService = myService;
        retrieveBlogs();
    }

    /**
     * retrieveBlogs()
     *  Retrieves a list of blogs from the server to be stored in the
     *  GoogleDataHandler.  Data can be passed to the classes by way
     *  of the listBlogs* methods.
     */
    public void retrieveBlogs() {
        Pattern blog_pt = Pattern.compile("blog-" + "\\d*");
        String[] cheese = {"error"};
        String[] cheese2 = {"error"};
        try {
            URL feedUrl = new URL(BLOGGER_URI + "default/blogs");
            Feed resultFeed = theService.getFeed(feedUrl, Feed.class);
            cheese = new String[resultFeed.getEntries().size()];
            cheese2 = new String[resultFeed.getEntries().size()];
            //Load each array with the blog names and ID's.
            for (int i = 0; i < resultFeed.getEntries().size(); i++) {
                Entry entry = resultFeed.getEntries().get(i);
                cheese[i] = entry.getTitle().getPlainText();
                //Now, split the ID from the getId() method for use later.
                Matcher mt = blog_pt.matcher(entry.getId());
                mt.find();
                String id = mt.group();
                id = id.substring(BLOG_ID_OFFSET);
                cheese2[i] = id;
                //...and throw it in the Hashtable.
                blogTable.put(cheese[i], cheese2[i]);
            }
        } catch (IOException ex) {
        } catch (ServiceException ex) {
        } catch (IllegalStateException exc) {
            System.out.println("Phail.");
        }
        list = cheese;
        rNumbers = cheese2;
    }

    public void retrievePosts(String blogID) {
        String[] wine = {"error"};
        String[] wine2 = {"error"};
        try {
            //Can't use a non-existing blog.
            if (blogID == null) {
                throw new IOException();
            }
            URL feedUrl = new URL(BLOGGER_URI + blogID + "/posts/default");
            Feed resultFeed = theService.getFeed(feedUrl, Feed.class);
            wine = new String[resultFeed.getEntries().size()];
            wine2 = new String[resultFeed.getEntries().size()];
            //Fill the arrays and Hashtable with relevant info.
            for (int i = 0; i < resultFeed.getEntries().size(); i++) {
                Entry entry = resultFeed.getEntries().get(i);
                wine[i] = entry.getTitle().getPlainText();
                wine2[i] = entry.getId().split("post-")[1];
                postTable.put(wine[i], wine2[i]);
            }
        } catch (IOException ex) {
        } catch (ServiceException ex) {
        } catch (IllegalStateException x) {
            System.out.println("Error.");
        }
        postNames = wine;
        postIds = wine2;
    }
    /**
     * retrievePostData()
     * pulls down from the server the data that comprises a blog entry.
     * @param blog_id the id of the blog we're retrieving from
     * @param post_id the id of the post we want
     * @return
     */
    public Entry retrievePostData(Object blog_id, Object post_id) {
        try {
            //pull down the list of posts...
            URL feedURL = new URL(BLOGGER_URI + blog_id + "/posts/default");
            Feed inFeed = theService.getFeed(feedURL, Feed.class);
            Entry[] post = new Entry[inFeed.getEntries().size()];
            //...fill the post array...
            for (int i = 0; i < inFeed.getEntries().size(); i++) {
                post[i] = inFeed.getEntries().get(i);
            }
            //...and, if we have it, send it to the user.
            for (Entry p : post) {
                if (p.getId().split("post-")[1].equals(post_id)) {
                    return p;
                }
                // do nothing - until the loop is done.
                else ;
            }
        } catch (java.net.MalformedURLException e) {
            System.out.println("Bad URL.");
        } catch (java.io.IOException e) {
            System.out.println("Data error.");
        } catch (com.google.gdata.util.ServiceException e) {
            System.out.println("Service error.");
        }return new Entry();
    }
    /**
 * listBlogsTitles()
 *  Send a list of titles for each blog to the user.
 * @return a list of blog titles.
 */

    public String[] listBlogsTitles() {
        return list;
    }
    /**
 * listBlogsIDs()
 *  Send a list of blog id's to the user.
 * @return a list of blog id's.
 */

    public String[] listBlogsIDs() {
        return rNumbers;
    }
    /**
 * listPostTitles()
 *  Send a list of titles for each post to the user.
 * @return a list of post titles
 */

    public String[] listPostTitles() {
        return postNames;
    }
    /**
 * listPostIDs()
 *  Send a list of post id's to the user.
 * @return a list of post id's.
 */

    public String[] listPostIDs() {
        return postIds;
    }

    public String blogIDFromName(Object name) throws IOException {
        String val = blogTable.get(name);
        if (val == null) {
            throw new IOException("Value not present.");
        } else {
            return val;
        }
    }

    public String postIDFromName(Object name) throws IOException {
        String val = postTable.get(name);
        if (val == null) {
            throw new IOException("Value not present.");
        } else {
            return val;
        }
    }
    /**
 * Create a post.
 * Currently, this is unfinished.
 * @param blogID the blog ID
 * @param title title of the post to be created.
 * @param content the contents of the post
 * @param authorName the author's name
 * @param userName the username uploading the post
 * @return Entry - the entry sent to the server
 * @throws com.google.gdata.util.ServiceException
 * @throws java.io.IOException
 */

    public Entry createPost(String title,
            Person user)
        throws ServiceException, IOException {
        // Create the entry to insert
        Entry myEntry = new Entry();
        myEntry.setTitle(new PlainTextConstruct(title));
        Person author = user;
        myEntry.getAuthors().add(author);
        return myEntry;
    }
    
    public Entry submitNewPost(String blogID, Entry newPost) 
        throws MalformedURLException, IOException, ServiceException{
        URL postURL = new URL("http://www.blogger.com/feeds/" + blogID + "/posts/default");
        return theService.insert(postURL, newPost);
    }
    public Entry updatePost(Entry toUpdate){
        try {
            URL updateURL = new URL(toUpdate.getEditLink().getHref());
            return theService.update(updateURL, toUpdate);
        } catch (IOException ex) {
            Logger.getLogger(GoogleDataHandler.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ServiceException ex) {
            Logger.getLogger(GoogleDataHandler.class.getName()).log(Level.SEVERE, null, ex);
        }
        return null; //If this happens, we're screwed. :)
    }
    public String[][] printAllComments(String blogID, 
      String postId) throws ServiceException, IOException {
    // Build comment feed URI and request comments on the specified post
    String commentsFeedUri = "http://www.blogger.com/feeds/" + blogID + "/" + postId + "/comments/default";
    URL feedUrl = new URL(commentsFeedUri);
    Feed resultFeed = theService.getFeed(feedUrl, Feed.class);

    // Display the results
    //System.out.println(resultFeed.getTitle().getPlainText());
    String[][] comment = new String[resultFeed.getEntries().size()][2];
    for (int i = 0; i < resultFeed.getEntries().size(); i++) {
      Entry entry = resultFeed.getEntries().get(i);
      comment[i][0]="Commented by: " + entry.getAuthors().get(0).getName() + " on " +entry.getUpdated().toString().substring(0,10);
      comment[i][1]=entry.getTitle().getPlainText();
    }
    System.out.println();
    return comment;
  }
}
